package com.ruoyi.shop.service.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.StringJoiner;

import com.ruoyi.common.exception.BusinessException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.shop.domain.*;
import com.ruoyi.shop.service.*;
import com.ruoyi.shop.util.GenNumberUtils;
import com.ruoyi.shop.util.pay.*;
import com.ruoyi.shop.vo.UserOrderVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.shop.mapper.ShopUserOrderMapper;
import com.ruoyi.common.core.text.Convert;
import org.springframework.transaction.annotation.Transactional;

/**
 * 订单Service业务层处理
 * 
 * @author Alan Zhang
 * @date 2021-09-14
 */
@Service
public class ShopUserOrderServiceImpl implements IShopUserOrderService 
{
    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private ShopUserOrderMapper shopUserOrderMapper;
    @Autowired
    private IShopUserCartService shopUserCartService;
    @Autowired
    private IShopCouponCodeService shopCouponCodeService;
    @Autowired
    private IShopCouponService shopCouponService;
    @Autowired
    private IShopUserOrderItemService shopUserOrderItemService;
    @Autowired
    private IShopProductService shopProductService;
    @Autowired
    private IShopUserAddressService shopUserAddressService;
    @Autowired
    private IShopUserOpenidService shopUserOpenidService;
    /**
     * 查询订单
     * 
     * @param id 订单主键
     * @return 订单
     */
    @Override
    public ShopUserOrder selectShopUserOrderById(Long id)
    {
        return shopUserOrderMapper.selectShopUserOrderById(id);
    }

    /**
     * 查询订单列表
     * 
     * @param shopUserOrder 订单
     * @return 订单
     */
    @Override
    public List<ShopUserOrder> selectShopUserOrderList(ShopUserOrder shopUserOrder)
    {
        return shopUserOrderMapper.selectShopUserOrderList(shopUserOrder);
    }

    /**
     * 新增订单
     * 
     * @param shopUserOrder 订单
     * @return 结果
     */
//    @Override
//    public int insertShopUserOrder(ShopUserOrder shopUserOrder)
//    {
//        shopUserOrder.setCreateTime(DateUtils.getNowDate());
//        return shopUserOrderMapper.insertShopUserOrder(shopUserOrder);
//    }

    /**
     * 新增订单
     *
     * @param shopUserOrder 订单
     * @return 结果
     */
    @Transactional
    @Override
    public int insertShopUserOrder(ShopUserOrder shopUserOrder)
    {
        shopUserOrder.setCreateTime(DateUtils.getNowDate());
        int rows = shopUserOrderMapper.insertShopUserOrder(shopUserOrder);
        insertShopUserOrderItem(shopUserOrder);
        return rows;
    }


    /**
     * 修改订单
     * 
     * @param shopUserOrder 订单
     * @return 结果
     */
    @Override
    public int updateShopUserOrder(ShopUserOrder shopUserOrder)
    {
        shopUserOrder.setUpdateTime(DateUtils.getNowDate());
        return shopUserOrderMapper.updateShopUserOrder(shopUserOrder);
    }


    /**
     * 批量删除订单
     *
     * @param ids 需要删除的订单主键
     * @return 结果
     */
    @Transactional
    @Override
    public int deleteShopUserOrderByIds(String ids)
    {
        shopUserOrderMapper.deleteShopUserOrderItemByOrderIds(Convert.toStrArray(ids));
        return shopUserOrderMapper.deleteShopUserOrderByIds(Convert.toStrArray(ids));
    }

    /**
     * 删除订单信息
     *
     * @param id 订单主键
     * @return 结果
     */
    @Override
    public int deleteShopUserOrderById(Long id)
    {
        shopUserOrderMapper.deleteShopUserOrderItemByOrderId(id);
        return shopUserOrderMapper.deleteShopUserOrderById(id);
    }

    /**
     * 新增订单明细信息
     *
     * @param shopUserOrder 订单对象
     */
    public void insertShopUserOrderItem(ShopUserOrder shopUserOrder)
    {
        List<ShopUserOrderItem> shopUserOrderItemList = shopUserOrder.getShopUserOrderItemList();
        Long id = shopUserOrder.getId();
        if (StringUtils.isNotNull(shopUserOrderItemList))
        {
            List<ShopUserOrderItem> list = new ArrayList<ShopUserOrderItem>();
            for (ShopUserOrderItem shopUserOrderItem : shopUserOrderItemList)
            {
                shopUserOrderItem.setOrderId(id);
                shopUserOrderItem.setOrderNs(shopUserOrder.getNs());
                list.add(shopUserOrderItem);
            }
            if (list.size() > 0)
            {
                shopUserOrderMapper.batchShopUserOrderItem(list);
            }
        }
    }

    /**
     * 删除订单信息
     * 
     * @param id 订单主键
     * @return 结果
     */
//    @Override
//    public int deleteShopUserOrderById(Long id)
//    {
//        return shopUserOrderMapper.deleteShopUserOrderById(id);
//    }

    /**
     * 根据订单号查询订单
     * @param orderNo
     * @return
     */
    @Override
    public ShopUserOrder selectShopUserOrderByOrderNo(String orderNo){
        return shopUserOrderMapper.selectShopUserOrderByOrderNo(orderNo);
    }
    /**
     * 修改订单备注
     * @param id
     * @param remark
     * @return
     */
    @Override
    public int updateShopUserOrderRemark(Long id, String remark){
        return shopUserOrderMapper.updateShopUserOrderRemark(id, remark);
    }


    /**
     * 立即购买 生成订单
     * @param userOrderVo 用户订单信息
     * @return
     */
    @Transactional
    @Override
    public ShopUserOrder genBuyOrder(UserOrderVo userOrderVo){
        ShopProduct shopProduct = shopProductService.selectShopProductById(userOrderVo.getProductId());
        if(shopProduct == null){
            throw new BusinessException("商品不存在");
        }
        ArrayList<ShopUserOrderItem> userOrderItems= new ArrayList<>();
        ShopUserOrderItem item = new ShopUserOrderItem();
        item.setBuyerId(userOrderVo.getUserId());
        item.setBuyerNickname(userOrderVo.getNickname());
        item.setWithRefund(1);
        item.setProductId(shopProduct.getId());
        item.setProductPrice(shopProduct.getPrice());
        item.setProductCount(userOrderVo.getQty());

        item.setDeliveryCost(BigDecimal.ZERO);//运费，后台设置
        item.setOtherCost(BigDecimal.ZERO); //其他费用

        item.setStatus(UserOrderItemConstants.STATUS_TRADING);// 交易中

        //payAmount = 产品价格 * 产品数量 + 运费 + 其他费用
        BigDecimal payAmount = shopProduct.getPrice().multiply(BigDecimal.valueOf(userOrderVo.getQty()))
                .add(item.getDeliveryCost())
                .add(item.getOtherCost());

        item.setPayAmount(payAmount);

        item.setTotalAmount(payAmount);

        userOrderItems.add(item);


        /** 创建订单 */
        ShopUserOrder userOrder = new ShopUserOrder();
        userOrder.setShopUserOrderItemList(userOrderItems);
        userOrder.setProductTitle(shopProduct.getTitle());
        userOrder.setDeliveryType(1);
        userOrder.setBuyerId(userOrderVo.getUserId());
        userOrder.setBuyerNickname(userOrderVo.getNickname());
        userOrder.setNs(GenNumberUtils.genOrderNS());

        //设置订单的产品描述
        userOrder.setProductSummary(shopProduct.getTitle());
        userOrder.setOrderTotalAmount(payAmount);
        userOrder.setOrderRealAmount(payAmount);

        userOrder.setPayStatus(PayStatus.UNPAY.getStatus());//支付状态：未支付
        userOrder.setTradeStatus(UserOrderConstants.TRADE_STATUS_TRADING);//交易状态：交易中...
        userOrder.setDeliveryStatus(UserOrderConstants.DELIVERY_STATUS_UNDELIVERY);//发货状态：未发货

        //保存 order
        insertShopUserOrder(userOrder);

        return userOrder;
    }

    /**
     * 用户下订单，开始购买
     * @param userOrderVo
     * @return
     */
    @Transactional
    @Override
    public ShopUserOrder genOrder(UserOrderVo userOrderVo) {
        /**
         * 创建订单项
         */
        ShopUserCart param = new ShopUserCart();
        param.setUserId(userOrderVo.getUserId());
        param.setSelected(1); //选中
        List<ShopUserCart> shopUserCartList = shopUserCartService.selectShopUserCartList(param);

        if (shopUserCartList == null || shopUserCartList.size() == 0) {
            throw new BusinessException("没有选择任何商品");
        }
        List<ShopUserOrderItem> userOrderItems = new ArrayList<>();

        //设置订单的产品描述
        StringJoiner stringJoiner = new StringJoiner(" ");
        StringJoiner userCartIds = new StringJoiner(",");
        String title = null;
        for (ShopUserCart userCart : shopUserCartList) {
            ShopProduct shopProduct = userCart.getShopProduct();
            if(StringUtils.isEmpty(title)){
                title = shopProduct.getTitle();
            }

            userCartIds.add(userCart.getId().toString());

            //用户返回重新提交
            if (userCart == null) {
                throw new BusinessException("该购物车信息已经提交，若需再次支付，请进入订单页面进行支付，或者重新下单。");
            }

            //有人去支付别人的产品？
            if (!userCart.getUserId().equals(userOrderVo.getUserId())){
                throw new BusinessException("发生错误，无法正确生成订单。");
            }

            if (shopProduct.getStatus() != 1) {
                throw new BusinessException("商品 " + shopProduct.getTitle() + " 已经下架。");
            }

            // 如果查询出来的 stock == null，表示 可以购买任意件商品
            Long stock = shopProduct.getStock();
            if (stock != null && stock <= 0) {
                throw new BusinessException("商品 " + shopProduct.getTitle() + " 已经库存不足。");
            }

            if (stock != null && stock < userCart.getProductCount()) {
                throw new BusinessException("商品 " + shopProduct.getTitle() + " 已经库存不足，目前只能购买 " + stock + " 件商品。");
            }

            ShopUserOrderItem item = new ShopUserOrderItem();
            item.setBuyerId(userCart.getUserId());
            item.setBuyerNickname(userOrderVo.getNickname());
            item.setWithRefund(1);
            item.setProductId(userCart.getProductId());
            item.setProductTitle(shopProduct.getTitle());
            item.setProductSpec(shopProduct.getSpecs());
            item.setProductPrice(shopProduct.getPrice());
            item.setProductCount(userCart.getProductCount());
            item.setDeliveryCost(BigDecimal.ZERO);//运费，后台设置
            item.setOtherCost(BigDecimal.ZERO); //其他费用

            item.setStatus(UserOrderItemConstants.STATUS_TRADING);// 交易中

            //payAmount = 产品价格 * 产品数量 + 运费 + 其他费用
            BigDecimal payAmount = shopProduct.getPrice().multiply(BigDecimal.valueOf(userCart.getProductCount()))
                    .add(item.getDeliveryCost())
                    .add(item.getOtherCost());

            item.setPayAmount(payAmount);

            item.setTotalAmount(payAmount);

            userOrderItems.add(item);

            stringJoiner.add(shopProduct.getTitle());
        }

        /** 创建订单 */
        ShopUserOrder userOrder = new ShopUserOrder();
        userOrder.setShopUserOrderItemList(userOrderItems);
        userOrder.setProductTitle(title);
        userOrder.setDeliveryType(1);
        userOrder.setBuyerId(userOrderVo.getUserId());
        userOrder.setBuyerMsg(userOrderVo.getBuyerMsg());
        userOrder.setBuyerNickname(userOrderVo.getNickname());
        userOrder.setNs(GenNumberUtils.genOrderNS());

        //设置订单的产品描述
        String productDesc = stringJoiner.toString();
        if (productDesc.length() > 200) {
            productDesc = productDesc.substring(0, 200) + "...";
        }

        userOrder.setProductSummary(productDesc.trim());

        //订单金额 = 所有 item 金额之和 - 优惠券金额
        BigDecimal orderTotalAmount = new BigDecimal(0);
        for (ShopUserOrderItem item : userOrderItems) {
            orderTotalAmount = orderTotalAmount.add(item.getPayAmount());
        }

        //设置优惠券的相关字段
        if (StringUtils.isNotBlank(userOrderVo.getCouponCode())) {
            ShopCouponCode shopCouponCode = shopCouponCodeService.findByCode(userOrderVo.getCouponCode());
            if (shopCouponCode == null) {
                throw new BusinessException("该优惠码不存");
            }
            boolean ret = shopCouponCodeService.valid(shopCouponCode, orderTotalAmount, userOrder.getBuyerId());

            ShopCoupon shopCoupon = shopCouponCode.getShopCoupon();

            //设置优惠码
            userOrder.setCouponCode(userOrderVo.getCouponCode());
            userOrder.setCouponAmount(shopCoupon.getAmount());
        }

        if (userOrder.getCouponAmount() != null) {
            //优惠劵大于 订单金额会导致 负数
            if (orderTotalAmount.compareTo(userOrder.getCouponAmount()) < 0) {
                orderTotalAmount = new BigDecimal(0);
            } else {
                orderTotalAmount = orderTotalAmount.subtract(userOrder.getCouponAmount());
            }
        }

        //余额
        if (PayType.AMOUNT.getType().equals(userOrderVo.getPayType())) {
//            BigDecimal userAmount = shopUserService.queryUserAmount(getLoginedUser().getId());
//            if (userAmount == null || userAmount.compareTo(orderTotalAmount) < 0) {
//                throw new BusinessException("用户余额不足，无法使用余额进行支付。");
//                return;
//            }
        }

        userOrder.setOrderTotalAmount(orderTotalAmount);
        userOrder.setOrderRealAmount(orderTotalAmount);

        userOrder.setPayStatus(PayStatus.UNPAY.getStatus());//支付状态：未支付
        userOrder.setTradeStatus(UserOrderConstants.TRADE_STATUS_TRADING);//交易状态：交易中...
        userOrder.setDeliveryStatus(UserOrderConstants.DELIVERY_STATUS_UNDELIVERY);//发货状态：未发货

        //收货地址
        ShopUserAddress userAddress = shopUserAddressService.selectShopUserAddressById(userOrderVo.getAddressId());
        userOrder.setDeliveryAddrUsername(userAddress.getUsername());
        userOrder.setDeliveryAddrMobile(userAddress.getMobile());
        userOrder.setDeliveryAddrProvince(userAddress.getProvince());
        userOrder.setDeliveryAddrCity(userAddress.getCity());
        userOrder.setDeliveryAddrDistrict(userAddress.getDistrict());
        userOrder.setDeliveryAddrDetail(userAddress.getDetail());
        userOrder.setDeliveryAddrZipcode(userAddress.getZipcode());

        //保存 order
        insertShopUserOrder(userOrder);

        if(userCartIds.length() > 0) {
            shopUserCartService.deleteShopUserCartByIds(userCartIds.toString());
        }
        return userOrder;
    }


    /**
     * 支付成功
     * @param paymentRecord
     */
    @Override
    public void paySuccess(ShopPaymentRecord paymentRecord){
        if (PaymentRecordConstants.TRX_TYPE_ORDER.equals(paymentRecord.getTrxType())) {

            ShopUserOrder entity = selectShopUserOrderById(paymentRecord.getId());

            ShopUserOrder userOrder = new ShopUserOrder();
            userOrder.setId(entity.getId());
            userOrder.setPayStatus(PayStatus.getSuccessIntStatusByType(paymentRecord.getPayType()));
            userOrder.setTradeStatus(UserOrderConstants.TRADE_STATUS_COMPLETED);

            int rows = updateShopUserOrder(userOrder);

            List<ShopUserOrderItem> userOrderItems = userOrder.getShopUserOrderItemList();
            ShopUserOrderItem orderItem = new ShopUserOrderItem();
            for (ShopUserOrderItem item : userOrderItems) {
                orderItem.setId(item.getId());
                orderItem.setStatus(UserOrderItemConstants.STATUS_COMPLETED);//交易完成
                shopUserOrderItemService.updateShopUserOrderItem(orderItem);
            }

            //增加积分
            //shopUserOpenidService.selectShopUserOpenidByUserId()
        }
    }


    /**
     * 支付失败
     * @param paymentRecord
     */
    @Override
    public void payFail(ShopPaymentRecord paymentRecord){

    }
}
